package com.kaifamiao.store.system.interceptor;

import com.fasterxml.jackson.databind.json.JsonMapper;
import com.kaifamiao.store.system.domain.User;
import com.kaifamiao.store.system.util.JwtUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);

        // 取请求头中的 token， key 是 token / Autorization。根据实际情况而定
        String jwt = request.getHeader("Authorization");

        if (StringUtils.hasText(jwt)){ // 有 jwt
            // 校验 jwt, 可能会有异常
            String subjectByToken = JwtUtils.getSubjectByToken(jwt);
            JsonMapper jsonMapper = new JsonMapper();
            User user = jsonMapper.readValue(subjectByToken, User.class);
            request.setAttribute("user", user);
            return true;
        }
        throw new RuntimeException("未登录");
    }
}
